package com.wanli.graalvmdemo.service;

import com.wanli.graalvmdemo.dao.UserRepository;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.ReactiveUserDetailsPasswordService;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService implements ReactiveUserDetailsService, ReactiveUserDetailsPasswordService {
    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    private final Map<String, UserDetails> users = new HashMap<>();

    @Resource
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserRepository userRepository;

    public Mono<UserDetails> findByUsername(String username) {
//        UserDetails user = User
//                .withUsername("admin")
//                .password(passwordEncoder().encode("password"))
//                .roles("USER")
//                .build();
//        return new MapReactiveUserDetailsService(user);

        return userRepository.findByUsername(username)
                .switchIfEmpty(Mono.error(new BadCredentialsException("账号或密码错误")))
                .map(user -> new User(
                        user.getUsername(),
                        user.getPassword(),
                        user.isEnabled(),
                        true,
                        true,
                        true,
                        Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
                ));
    }

    @Override
    public Mono<UserDetails> updatePassword(UserDetails user, String newPassword) {
        return Mono.just(user)
                .map(u -> User.withUserDetails(u)
                        .password(newPassword)
                        .build()
                )
                .doOnNext(u -> {
                    this.users.put(user.getUsername().toLowerCase(), u);
                });
    }
}